package fdoj.eventInvitations.servlet;

import java.io.IOException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gdata.client.contacts.*;
import com.google.gdata.client.http.*;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

import fdoj.eventInvitations.dao.PersonDao;
import fdoj.eventInvitations.entity.Contact;
import fdoj.eventInvitations.entity.Person;

public class ImportContacts extends HttpServlet {

	@EJB
	PersonDao personDao;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession();
			if (session != null) {
				Person loggedUser = null;
				if ((loggedUser = (Person) session.getAttribute("loggedUser")) != null) {
					System.out.println(session.getAttribute("importContacts"));
					HashMap<Integer, Contact> importContacts = (HashMap<Integer, Contact>) session
							.getAttribute("importContacts");
					String[] ids = request.getParameterValues("contactId");
					if (ids != null) {
						for (String id : ids) {
							Contact c=importContacts.get(Integer
									.valueOf(id));
							c.setId(null);
							loggedUser.addContact(c);
						}
					}
					personDao.merge(loggedUser);
					Person pp = personDao.findById(loggedUser.getId());
					session.setAttribute("loggedUser", pp);
					response.sendRedirect("./addressbook");
					return;
				}
			}
			else{
				response.sendRedirect(response.encodeRedirectURL("./index"));
				return;
			}
			response.sendRedirect(response.encodeRedirectURL("./index"));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
